//
//  ViewController.swift
//  ShimaPlayer
//
//  Created by Miracolo Bosco on 2025/7/3.
//

import SnapKit
import UIKit

class ViewController: UIViewController {

    // MARK: - UI 组件
    private lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_nav_dismiss")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "250307C1新编第2册单词词单"
        label.textColor = UIColor(hexString: "FFFFFF")?.withAlphaComponent(0.66)
        label.font = .systemFont(ofSize: 15, weight: .bold)
        label.textAlignment = .center
        return label
    }()

    private lazy var wordListTableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(WordCell.self, forCellReuseIdentifier: "WordCell")
        return tableView
    }()

    private lazy var progressSlider: CustomSlider = {
        let slider = CustomSlider()
        slider.minimumTrackTintColor = UIColor(hexString: "FFFFFF")
        slider.maximumTrackTintColor = UIColor(hexString: "BABDCA")
        let config = UIImage.SymbolConfiguration(pointSize: 4, weight: .regular)
        slider.setThumbImage(
            UIImage(systemName: "circle.fill", withConfiguration: config)?.withTintColor(
                .white, renderingMode: .alwaysOriginal), for: .normal)
        slider.value = 0.0
        slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged)
        slider.addTarget(self, action: #selector(sliderTouchBegan), for: .touchDown)
        slider.addTarget(
            self, action: #selector(sliderTouchEnded),
            for: [.touchUpInside, .touchUpOutside, .touchCancel])
        return slider
    }()

    private lazy var currentTimeLabel: UILabel = {
        let label = UILabel()
        label.text = "00:00"
        label.textColor = UIColor(hexString: "BABDCA")
        label.font = .systemFont(ofSize: 9)
        return label
    }()

    private lazy var playbackModeLabel: UILabel = {
        let label = UILabel()
        label.text = "自动播放"
        label.textColor = UIColor(hexString: "BABDCA")
        label.font = .systemFont(ofSize: 9)
        label.textAlignment = .center
        return label
    }()

    private lazy var totalTimeLabel: UILabel = {
        let label = UILabel()
        label.text = "00:00"
        label.textColor = UIColor(hexString: "BABDCA")
        label.font = .systemFont(ofSize: 9)
        label.textAlignment = .right
        return label
    }()

    private lazy var repeatButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_repeat")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(playModeButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var previousButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_previous")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(previousButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var playPauseButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_pause")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(playPauseButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var nextButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_next")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var settingsButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_settings")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(settingsButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var favoriteButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_heart")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(favouriteButtonTapped), for: .touchUpInside)
        return button
    }()

    private lazy var listenButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(
            UIImage(named: "btn_listen")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(listenButtonTapped), for: .touchUpInside)
        return button
    }()

    // Language display mode enum
    enum LanguageDisplayMode: Int, CaseIterable {
        case both = 0  // 显示日文和中文
        case chineseOnly = 1  // 只显示中文
        case japaneseOnly = 2  // 只显示日文

        var title: String {
            switch self {
            case .both: return "日/中 显示日文和中文"
            case .chineseOnly: return "日/中 只显示中文"
            case .japaneseOnly: return "日/中 只显示日文"
            }
        }

        var buttonTitle: String {
            return "日/中"
        }
    }

    // Current language display mode
    private var currentLanguageMode: LanguageDisplayMode = .both {
        didSet {
            updateLanguageSwitchButton()
            // TODO: 这里应该更新单词列表的显示
            wordListTableView.reloadData()
        }
    }

    private lazy var languageSwitchButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle(LanguageDisplayMode.both.buttonTitle, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 10, weight: .medium)
        button.setTitleColor(UIColor(hexString: "BABDCA"), for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 10, weight: .medium)
        button.layer.borderWidth = 0.7
        button.layer.borderColor = UIColor(hexString: "BABDCA")?.cgColor
        button.layer.cornerRadius = 10
        button.addTarget(self, action: #selector(languageSwitchButtonTapped), for: .touchUpInside)
        return button
    }()

    // 歌词数据结构（带有时间戳）
    private struct LyricLine {
        let text: String
        let startTime: TimeInterval  // 开始时间（秒）
        let endTime: TimeInterval  // 结束时间（秒）
    }

    // 带有时间戳的示例歌词数据
    private let lyrics: [LyricLine] = [
        LyricLine(text: "签证", startTime: 0.0, endTime: 5.0),
        LyricLine(text: "请多多关照", startTime: 5.0, endTime: 10.0),
        LyricLine(text: "猫", startTime: 10.0, endTime: 15.0),
        LyricLine(text: "雪", startTime: 15.0, endTime: 20.0),
        LyricLine(text: "哪儿的话...岂敢岂敢", startTime: 20.0, endTime: 25.0),
        LyricLine(text: "饭店，旅馆", startTime: 25.0, endTime: 30.0),
        LyricLine(text: "快乐、轻松；舒服的", startTime: 30.0, endTime: 35.0),
        LyricLine(text: "钢笔", startTime: 35.0, endTime: 40.0),
        LyricLine(text: "(答应声) 是，是的", startTime: 40.0, endTime: 45.0),
        LyricLine(text: "外出，不在家", startTime: 45.0, endTime: 50.0),
    ]

    private var isLike = false
    private var isRandom = false

    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupPlayback()
    }

    // MARK: - UI 设置
    private func setupUI() {
        setupBackground()
        setupNavigationElements()
        setupWordList()
        setupProgressBar()
        setupPlaybackControls()
    }

    private func setupBackground() {
        view.backgroundColor = UIColor(red: 0.106, green: 0.137, blue: 0.251, alpha: 1)

        let backgroundView = UIView()
        backgroundView.frame = UIScreen.main.bounds

        let layer0 = CAGradientLayer()
        layer0.colors = [
            UIColor(red: 0.106, green: 0.137, blue: 0.251, alpha: 1).cgColor,
            UIColor(red: 0.11, green: 0.137, blue: 0.255, alpha: 1).cgColor,
            UIColor(red: 0.15, green: 0.182, blue: 0.31, alpha: 1).cgColor,
            UIColor(red: 0.208, green: 0.247, blue: 0.392, alpha: 1).cgColor,
            UIColor(red: 0.212, green: 0.247, blue: 0.396, alpha: 1).cgColor,
        ]
        layer0.locations = [0.12, 0.45, 0.56, 0.8, 1]
        layer0.startPoint = CGPoint(x: 0.25, y: 0.5)
        layer0.endPoint = CGPoint(x: 0.75, y: 0.5)
        layer0.transform = CATransform3DMakeAffineTransform(
            CGAffineTransform(a: 0, b: 1.05, c: -1.05, d: 0, tx: 1.03, ty: -0.01))

        let extraSize: CGFloat = 100.0
        layer0.frame = backgroundView.bounds.insetBy(dx: -extraSize, dy: -extraSize)

        backgroundView.layer.addSublayer(layer0)

        view.insertSubview(backgroundView, at: 0)
        backgroundView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    private func setupNavigationElements() {
        view.addSubview(backButton)
        view.addSubview(titleLabel)

        backButton.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(10)
            make.leading.equalToSuperview().offset(20)
            make.width.height.equalTo(30)
        }

        titleLabel.snp.makeConstraints { make in
            make.centerY.equalTo(backButton)
            make.centerX.equalToSuperview()
            make.leading.greaterThanOrEqualTo(backButton.snp.trailing).offset(10)
            make.trailing.lessThanOrEqualToSuperview().offset(-20)
        }
    }

    private func setupWordList() {
        // 添加带有中心线指示器的容器视图
        let containerView = UIView()
        containerView.backgroundColor = .clear
        view.addSubview(containerView)

        // 添加中心指示线
        //        let centerLineView = UIView()
        //        centerLineView.backgroundColor = UIColor.white.withAlphaComponent(0.2)
        //        centerLineView.layer.cornerRadius = 1
        //        containerView.addSubview(centerLineView)

        // 将 tableView 添加到容器中
        containerView.addSubview(wordListTableView)

        // 设置容器的约束
        containerView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.leading.equalToSuperview().offset(20)
            make.trailing.equalToSuperview().offset(-20)
            make.bottom.equalTo(view.snp.bottom).offset(-260)
        }

        // 设置中心线的约束
        //        centerLineView.snp.makeConstraints { make in
        //            make.leading.trailing.equalToSuperview().inset(30)
        //            make.height.equalTo(2)
        //            make.center.equalToSuperview()
        //        }

        // 设置 tableView 的约束
        wordListTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        // 添加空的头部和尾部以允许居中
        wordListTableView.tableHeaderView = UIView(
            frame: CGRect(x: 0, y: 0, width: 0, height: containerView.frame.height / 2 - 25))
        wordListTableView.tableFooterView = UIView(
            frame: CGRect(x: 0, y: 0, width: 0, height: containerView.frame.height / 2 - 25))

        // 滚动到第一个歌词
        scrollToCurrentLyric(animated: false)
    }

    private func setupProgressBar() {
        view.addSubview(progressSlider)
        view.addSubview(currentTimeLabel)
        view.addSubview(playbackModeLabel)
        view.addSubview(totalTimeLabel)

        progressSlider.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.height.equalTo(1)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-158)
        }

        currentTimeLabel.snp.makeConstraints { make in
            make.top.equalTo(progressSlider.snp.bottom).offset(10)
            make.leading.equalTo(progressSlider)
        }

        playbackModeLabel.snp.makeConstraints { make in
            make.top.equalTo(progressSlider.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
        }

        totalTimeLabel.snp.makeConstraints { make in
            make.top.equalTo(progressSlider.snp.bottom).offset(10)
            make.trailing.equalTo(progressSlider)
        }

        // 初始化时间标签
        updateTimeLabels()
    }

    private func setupPlaybackControls() {
        let controlsStackView = UIStackView(arrangedSubviews: [
            repeatButton, previousButton, playPauseButton, nextButton, settingsButton,
        ])
        controlsStackView.axis = .horizontal
        controlsStackView.distribution = .equalSpacing
        controlsStackView.alignment = .center

        view.addSubview(controlsStackView)
        view.addSubview(languageSwitchButton)
        view.addSubview(favoriteButton)
        view.addSubview(listenButton)

        controlsStackView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(20)
            make.trailing.equalToSuperview().offset(-20)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-66)
        }

        // Make the play/pause button larger
        playPauseButton.snp.makeConstraints { make in
            make.width.height.equalTo(60)
        }

        // Other buttons standard size
        [repeatButton, previousButton, nextButton, settingsButton].forEach { button in
            button.snp.makeConstraints { make in
                make.width.height.equalTo(30)
            }
        }

        languageSwitchButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(20)
            make.bottom.equalTo(controlsStackView.snp.top).offset(-90)
            make.width.equalTo(46)
            make.height.equalTo(17)
        }

        listenButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-20)
            make.centerY.equalTo(languageSwitchButton)
            make.width.height.equalTo(30)
        }

        favoriteButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-64)
            make.centerY.equalTo(languageSwitchButton)
            make.width.height.equalTo(30)
        }
    }

    // MARK: - Properties
    private var currentTime: TimeInterval = 0.0
    private var totalDuration: TimeInterval = 50.0
    private var isUserInteractingWithSlider = false
    private var currentLyricIndex = 0
    private var playbackTimer: Timer?

    // MARK: - Actions
    @objc private func backButtonTapped() {
//        showTooltip(with: "点击返回")
        let vc = TestViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

    @objc private func languageSwitchButtonTapped() {
        let nextModeRawValue =
            (currentLanguageMode.rawValue + 1) % LanguageDisplayMode.allCases.count
        if let nextMode = LanguageDisplayMode(rawValue: nextModeRawValue) {
            currentLanguageMode = nextMode

        }
    }

    @objc private func playModeButtonTapped() {
        isRandom.toggle()
        repeatButton.setImage(
            UIImage(named: isRandom ? "btn_random" : "btn_repeat")?.withRenderingMode(
                .alwaysOriginal), for: .normal)
    }

    @objc private func favouriteButtonTapped() {
        isLike.toggle()
        favoriteButton.setImage(
            UIImage(named: isLike ? "btn_heart_selected" : "btn_heart")?.withRenderingMode(
                .alwaysOriginal), for: .normal)
    }

    private func updateLanguageSwitchButton() {
        var title: NSAttributedString
        switch currentLanguageMode {
        case .both:
            title = NSMutableAttributedString(string: "日/中")
        case .chineseOnly:
            title = NSMutableAttributedString(string: "日/中").setColor(
                for: "日/", color: UIColor(hexString: "FFFFFF")?.withAlphaComponent(0.2) ?? .white)
        case .japaneseOnly:
            title = NSMutableAttributedString(string: "日/中").setColor(
                for: "/中", color: UIColor(hexString: "FFFFFF")?.withAlphaComponent(0.2) ?? .white)
        }
        languageSwitchButton.setAttributedTitle(title, for: .normal)
    }

    @objc private func settingsButtonTapped() {
        showTooltip(with: "点击设置")
    }

    @objc private func previousButtonTapped() {
        showTooltip(with: "点击上一首")
    }

    @objc private func nextButtonTapped() {
        showTooltip(with: "点击下一首")
    }

    @objc private func listenButtonTapped() {
        showTooltip(with: "点击收听")
    }
}

// MARK: - UITableViewDelegate & UITableViewDataSource
extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lyrics.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =
            tableView.dequeueReusableCell(withIdentifier: "WordCell", for: indexPath) as! WordCell

        // 计算与当前索引的距离，用于渐变效果
        let distanceFromCurrent = abs(indexPath.row - currentLyricIndex)

        // 确定这是否是过去的歌词（在当前歌词之前）
        let isPastLyric = indexPath.row < currentLyricIndex

        // 使用文本和渐变效果配置单元格
        cell.configure(
            with: lyrics[indexPath.row].text,
            isHighlighted: indexPath.row == currentLyricIndex,
            distanceFromCurrent: distanceFromCurrent,
            isPastLyric: isPastLyric
        )

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
}

// MARK: - WordCell
//class WordCell: UITableViewCell {
//    private let wordLabel: UILabel = {
//        let label = UILabel()
//        label.textColor = .white
//        label.font = .systemFont(ofSize: 16)
//        label.textAlignment = .center
//        return label
//    }()
//
//    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
//        super.init(style: style, reuseIdentifier: reuseIdentifier)
//        setupCell()
//    }
//
//    required init?(coder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//
//    private func setupCell() {
//        backgroundColor = .clear
//        selectionStyle = .none
//
//        contentView.addSubview(wordLabel)
//        wordLabel.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
//        }
//    }
//
//    func configure(
//        with word: String, isHighlighted: Bool = false, distanceFromCurrent: Int = 0,
//        isPastLyric: Bool = false
//    ) {
//        wordLabel.text = word
//
//        // 渐变效果考虑的最大距离
//        let maxDistance = 5
//
//        // 根据与当前歌词的距离应用渐变效果
//        if isHighlighted {
//            // 当前歌词 - 蓝色，不透明度为 100%
//            wordLabel.textColor = UIColor(hexString: "FFFFFF")
//            wordLabel.font = .systemFont(ofSize: 17, weight: .medium)
//        } else {
//            // 根据距离计算透明度（越近 = 越可见）
//            let alpha = max(1.0 - (Double(distanceFromCurrent) / Double(maxDistance)), 0.3)
//
//            // 为过去的歌词应用额外的淡出效果
//            if isPastLyric {
//                // 过去的歌词有不同的颜色和降低的不透明度
//                let pastLyricAlpha = max(alpha * 0.7, 0.3)  // 比未来歌词更透明
//                //                wordLabel.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.8, alpha: CGFloat(pastLyricAlpha))
//                wordLabel.textColor = UIColor(hexString: "FFFFFF")?.withAlphaComponent(
//                    CGFloat(pastLyricAlpha))
//            } else {
//                // 未来歌词保持白色，透明度根据计算结果
//                wordLabel.textColor = UIColor(hexString: "FFFFFF")?.withAlphaComponent(
//                    CGFloat(alpha))
//            }
//
//            wordLabel.font = .systemFont(ofSize: 15, weight: .medium)
//        }
//    }
//}

// MARK: - Playback Control Extension
extension ViewController {
    // MARK: - 播放控制

    private func setupPlayback() {
        // 初始化播放定时器
        startPlaybackTimer()

        // 更新 UI 以反映初始状态
        updateTimeLabels()
        updateProgressSlider()
    }

    private func startPlaybackTimer() {
        // 取消现有的定时器（如果有）
        playbackTimer?.invalidate()

        // 创建一个每 0.1 秒触发一次的新定时器
        playbackTimer = Timer.scheduledTimer(
            timeInterval: 0.1, target: self, selector: #selector(updatePlayback), userInfo: nil,
            repeats: true)
    }

    @objc private func updatePlayback() {
        // 跳过用户与滑块交互时的更新
        if isUserInteractingWithSlider {
            return
        }

        // 更新当前时间（模拟播放）
        currentTime += 0.1
        if currentTime > totalDuration {
            currentTime = 0.0
        }

        // 更新 UI
        updateTimeLabels()
        updateProgressSlider()
        updateCurrentLyric()
    }

    private func updateTimeLabels() {
        // 计算和格式化进度百分比
        let progressPercentage = Int((currentTime / totalDuration) * 100)
        currentTimeLabel.text = String(format: "%d%%", progressPercentage)

        // 显示当前歌词索引和总歌词数
        totalTimeLabel.text = String(format: "%d/%d", currentLyricIndex + 1, lyrics.count)
    }

    private func updateProgressSlider() {
        // 根据当前时间更新滑块值
        progressSlider.value = Float(currentTime / totalDuration)
    }

    private func updateCurrentLyric() {
        // 根据当前时间查找当前歌词
        var newLyricIndex = 0
        for (index, lyric) in lyrics.enumerated() {
            if currentTime >= lyric.startTime && currentTime < lyric.endTime {
                newLyricIndex = index
                break
            }
        }

        // 如果歌词索引发生变化，更新 UI
        if newLyricIndex != currentLyricIndex {
            let oldIndex = currentLyricIndex
            currentLyricIndex = newLyricIndex

            // 更新单元格
            wordListTableView.reloadRows(
                at: [
                    IndexPath(row: oldIndex, section: 0), IndexPath(row: newLyricIndex, section: 0),
                ], with: .none)

            // 滚动到当前歌词
            scrollToCurrentLyric(animated: true)
        }
    }

    private func scrollToCurrentLyric(animated: Bool) {
        if currentLyricIndex < lyrics.count {
            wordListTableView.scrollToRow(
                at: IndexPath(row: currentLyricIndex, section: 0), at: .middle, animated: animated)
        }
    }

    // 视图布局完成后更新头部和尾部高度
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // 确保头部和尾部大小正确，以便居中
        let cellHeight: CGFloat = 50  // 来自 tableView 代理的单元格高度
        let visibleHeight = wordListTableView.bounds.height
        let headerFooterHeight = (visibleHeight - cellHeight) / 2

        if wordListTableView.tableHeaderView?.frame.height != headerFooterHeight {
            wordListTableView.tableHeaderView = UIView(
                frame: CGRect(
                    x: 0, y: 0, width: wordListTableView.bounds.width, height: headerFooterHeight))
            wordListTableView.tableFooterView = UIView(
                frame: CGRect(
                    x: 0, y: 0, width: wordListTableView.bounds.width, height: headerFooterHeight))

            // 更新头部/尾部后重新滚动到当前歌词
            if currentLyricIndex < lyrics.count {
                wordListTableView.scrollToRow(
                    at: IndexPath(row: currentLyricIndex, section: 0), at: .middle, animated: false)
            }
        }
    }

    // MARK: - 用户交互处理

    @objc private func sliderValueChanged() {
        // 根据滑块值计算新时间
        let newTime = Double(progressSlider.value) * totalDuration

        // Update current time
        currentTime = newTime

        // Update UI
        updateTimeLabels()
        updateCurrentLyric()
    }

    @objc private func sliderTouchBegan() {
        // 设置标志以防止用户交互时的定时器更新
        isUserInteractingWithSlider = true
    }

    @objc private func sliderTouchEnded() {
        // 清除标志以恢复定时器更新
        isUserInteractingWithSlider = false
    }

    @objc private func playPauseButtonTapped() {
        // 切换播放状态
        if playbackTimer?.isValid == true {
            // 暂停播放
            playbackTimer?.invalidate()
            playPauseButton.setImage(
                UIImage(named: "btn_play")?.withRenderingMode(.alwaysOriginal), for: .normal)
        } else {
            // 恢复播放
            startPlaybackTimer()
            playPauseButton.setImage(
                UIImage(named: "btn_pause")?.withRenderingMode(.alwaysOriginal), for: .normal)
        }
    }

    // MARK: - TableView 交互

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 更新当前歌词索引
        currentLyricIndex = indexPath.row

        // 根据选定的歌词更新当前时间
        currentTime = lyrics[indexPath.row].startTime

        // Update UI
        updateTimeLabels()
        updateProgressSlider()
        wordListTableView.reloadData()
    }
}

// TODO: 临时toast
extension ViewController {
    private func showTooltip(with message: String) {
        // Create tooltip view
        let tooltipView = UIView()
        tooltipView.backgroundColor = UIColor(white: 0.2, alpha: 0.8)
        tooltipView.layer.cornerRadius = 15
        tooltipView.alpha = 0
        tooltipView.tag = 1001  // Tag for easy removal

        // Create tooltip label
        let tooltipLabel = UILabel()
        tooltipLabel.text = message
        tooltipLabel.textColor = .white
        tooltipLabel.font = .systemFont(ofSize: 14)
        tooltipLabel.textAlignment = .center
        tooltipLabel.numberOfLines = 0

        // Add tooltip to view hierarchy
        view.addSubview(tooltipView)
        tooltipView.addSubview(tooltipLabel)

        // Setup constraints
        tooltipView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(languageSwitchButton.snp.bottom).offset(10)
            make.width.lessThanOrEqualToSuperview().offset(-40)
        }

        tooltipLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(
                UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12))
        }

        // Animate tooltip appearance
        UIView.animate(
            withDuration: 0.3,
            animations: {
                tooltipView.alpha = 1
            }
        ) { _ in
            // Animate tooltip disappearance after delay
            UIView.animate(
                withDuration: 0.3, delay: 2.0, options: [],
                animations: {
                    tooltipView.alpha = 0
                }
            ) { _ in
                tooltipView.removeFromSuperview()
            }
        }
    }
}

//class CustomSlider: UISlider {
//
//    var sliderHeight: CGFloat = 1
//
//    override func minimumValueImageRect(forBounds bounds: CGRect) -> CGRect {
//        return self.bounds
//    }
//
//    override func maximumValueImageRect(forBounds bounds: CGRect) -> CGRect {
//        return self.bounds
//    }
//
//    override func trackRect(forBounds bounds: CGRect) -> CGRect {
//        let rect = super.trackRect(forBounds: bounds)
//        layer.cornerRadius = sliderHeight / 2
//        return CGRect.init(
//            x: rect.origin.x, y: (bounds.size.height - sliderHeight) / 2, width: bounds.size.width,
//            height: sliderHeight)
//    }
//
//    override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float)
//        -> CGRect
//    {
//        return super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
//    }
//
//}
